import { memo, useEffect, useMemo, useRef, useState } from "react"
import { WindowCompPropsType } from "./types"
import styles from './styles.module.less'
import { Icon, Portal, useData, Image, getClassNames } from "magic-ui-react"
import { isEmpty, isFunction, isNil, isNull, isUndefined } from "lodash"
import { store } from "@/store"
import { CSSTransition } from "react-transition-group"
import './styles.less'
const WindowComp = (props: WindowCompPropsType) => {
  const appConfig = store.getState().appConfig
  const {
    width = '850px',
    height = '500px',
    title,
    icon,
    header,
    content,
    footer,
    radius = 6,
    iconImage,
    harf,
    iconSingleClick,
    firstRender,
    background,
  } = props

  const dialogRef = useRef<HTMLDialogElement>(null)

  const [windowSize, setWindowSize] = useState<{
    width: string | number,
    height: string | number,
  }>({
    width,
    height,
  })

  const iconBoxRef = useRef(null)

  const data = useData({
    // 是否已经渲染
    isRender: false,
    // 是否为关闭
    off: false,
    lastTransform: 'translate(0px, 0px)'
  })


  const [visible, setVisible] = useState(false)

  const [hidden, setHidden] = useState(true)

  const [isScreen, setIsSrceen] = useState(false)

  useEffect(() => {
    changeTransition('add')
    if (isScreen) {
      if (dialogRef.current) {
        data.lastTransform = dialogRef.current.style.transform
        dialogRef.current.style.transform = `translate(0px, 0px)`
      }
    } else {
      if (dialogRef.current) {
        dialogRef.current.style.transform = data.lastTransform
      }
    }
  }, [isScreen])

  const clear = () => {
    document.onmousemove = null
    data.lastTransform = `translate(0px, 0px)`
    setIsSrceen(false)
  }

  const changeTransition = (type: 'delete' | 'add') => {
    if (!dialogRef.current) {
      return
    }
    if (type === 'add') {
      dialogRef.current.style.transition = 'all 0.2s'
    }
    if (type === 'delete') {
      dialogRef.current.style.transition = 'unset'
    }
  }

  useEffect(() => {
    return () => {
      clear()
    }
  }, [])

  /**
   * 窗口顶部
   * @returns TopBar
   */
  const topBarRender = () => {
    if (isUndefined(header)) {
      return (
        <nav
          onMouseDown={(event1) => {
            if (dialogRef.current) {
              changeTransition('delete')
              const translateArr = dialogRef.current.style.transform.replace(/translate|\)|\(| |px/g, '').split(',')
              const initTranslateX = Number(translateArr[0])
              const initTranslateY = Number(translateArr[1])
              document.onmousemove = (event) => {
                if (dialogRef.current) {
                  let moveX = event.clientX - event1.clientX
                  let moveY = event.clientY - event1.clientY
                  dialogRef.current.style.transform = `translate(${initTranslateX + moveX}px, ${initTranslateY + moveY}px)`
                }
              }
            }
          }}
          onMouseUp={() => {
            document.onmousemove = null
          }}
          // draggable
          className={styles.topBar}>
          <div className={styles.title}>
            {title}
          </div>
          <ol className={styles.options}>
            <li
              className={getClassNames([
                styles.option,
              ])}
              onClick={(e) => {
                e.stopPropagation()
                changeTransition('add')
                data.off = false
                setHidden(true)
              }}
            >
              <Icon icon="minus" size={20} />
            </li>
            <li
              className={getClassNames([
                styles.option,
                styles.isScreen
              ])}
              onClick={(e) => {
                setIsSrceen(!isScreen)
              }}
            >
              <Icon icon="clone" size={16} />
            </li>
            <li
              className={getClassNames([
                styles.option,
              ])}
              onClick={(e) => {
                e.stopPropagation()
                changeTransition('add')
                data.off = true
                setHidden(true)
              }}
            >
              <Icon icon="xmark" size={20} />
            </li>
          </ol>
        </nav>
      )
    } else {
      return (
        <nav>
          {header}
        </nav>
      )
    }
  }

  /**
   * 窗口主体
   * @returns Main
   */
  const mainRender = useMemo(() => {
    if (harf) {
      return (
        <iframe
          src={harf}
          width={'100%'}
          height={'100%'}
        ></iframe>
      )
    } else {
      return (
        <main className={styles.main} >
          {isFunction(content) ? content({ isScreen, visible }) : content}
        </main>
      )
    }
  }, [visible, content])

  /**
   * 窗口底部
   * @returns Footer
   */
  const footerRender = () => {
    if (!isEmpty(footer)) {
      return (
        <footer className={styles.footer}>
          {footer}
        </footer>
      )
    }
  }

  /**
   * 窗口按钮
   * @returns Icon
   */
  const iconRender = () => {
    if (iconImage) {
      return (
        <img
          alt="icon"
          width='50%'
          height='50%'
          src={iconImage}
        />
      )
    } else {
      return (
        <>
          {isFunction(icon) ? icon(visible) : icon}
        </>
      )
    }
  }

  return (
    <>
      <div
        className={styles.icon}
        ref={iconBoxRef}
        onClick={(event) => {
          iconSingleClick?.(event)
          if (!data.isRender) {
            firstRender?.()
            setVisible(true)
            data.isRender = true
            setHidden(false)
          } else {
            setHidden(!hidden)
          }
        }}
      >
        {iconRender()}
      </div>
      <CSSTransition
        in={!hidden}
        timeout={200}
        nodeRef={dialogRef}
        classNames={'windowComp'}
        onExited={() => {
          if (data.off) {
            data.isRender = false
            data.off = false
            setVisible(false)
            clear()
          }
        }}
        unmountOnExit={!visible}
      >
        <Portal forceRender={true} container={document.querySelector('#windowContent')!} >
          <dialog
            ref={dialogRef}
            // 按下鼠标后提高当前点击Dialog层级
            onMouseDown={(event) => {
              event.currentTarget.parentElement?.childNodes.forEach((e: any) => {
                e.style.zIndex = '1'
              })
              event.currentTarget.style.zIndex = '2'
            }}
            // 阻止冒泡默认事件
            onClick={(event) => {
              event.stopPropagation()
              event.preventDefault()
            }}
            className={getClassNames([
              styles.windowComp,
              {
                [styles.windowCompScreen]: isScreen
              },
            ])}
            style={{
              transform: `translate(0px, 0px)`,
              width: windowSize.width,
              height: windowSize.height,
            }}
          >
            <div className={styles.contentBg}>
              {isFunction(background) ? background() : background}
            </div>
            <div
              className={getClassNames([
                styles.content,
              ])}
              style={{
                gridTemplateRows: isNull(footer) ? `40px 1fr` : `40px 1fr auto`,
              }}
            >
              {topBarRender()}
              {mainRender}
              {footerRender()}
            </div>
          </dialog>
        </Portal >
      </CSSTransition>
    </>
  )
}

export default memo(WindowComp)